package com.sun.dailyprj.view;


import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.ContentLoadingProgressBar;

import com.sun.dailyprj.util.Logger;

public class NonLineProgressBar extends ContentLoadingProgressBar{

    private int mInflectPointer; //进度条分段点数，比如三段则有两个拐点
    private int mCurInflectPointer = 0;//当前进度值拐点位置。
    private int mCurProgress = 0;//当前进度值
    private int mMax = 100;
    private int mMin = 0;
    private CountDownTimer mCountDownTimer;
    private int mExpectedTime = 5*60*1000;//5min

    public NonLineProgressBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setRules(int inflectPoint,int expectedTime) {
        if(inflectPoint > mMax || inflectPoint < mMin)
            try{
                throw new Exception("Inflection point number set is not reasonable ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        this.mInflectPointer = inflectPoint;
            this.mExpectedTime = expectedTime;
    }

    @Override
    public synchronized void setProgress(int progress) {
//        super.setProgress(progress);
        super.setProgress(mCurProgress);
        if(progress == mMin){
//            initCountDownTimer();
        }
        if(mCurInflectPointer == progress){
            //在当前拐点内，无需更新大的进度值
        }else {
            mCurInflectPointer = progress;
            mCurProgress = mCurInflectPointer * (mMax - mMin)/(mInflectPointer + 1);
        }
        if(mCurProgress == mMax) {
            mCountDownTimer.cancel();
        }
        Logger.info("mCurProgress:" + mCurProgress);

    }

    @Override
    public synchronized void setMax(int max) {
        super.setMax(max);
        mMax = max;
    }

    @Override
    public synchronized void setMin(int min) {
        super.setMin(min);
        this.mMin = min;
    }

    //默认匀速升级中，获取到某个ecu安装完成后，进度值则直接跳到对应百分比上去，然后再继续慢慢的更新。
    private void initCountDownTimer(){
        mCountDownTimer = new CountDownTimer(1000*(mMax-mMin)/(mInflectPointer + 1),mExpectedTime){
            @Override
            public void onTick(long millisUntilFinished) {
                mCurProgress ++;
                Logger.info("onTick() :mCurProgress:" + mCurProgress);
            }

            @Override
            public void onFinish() {

            }
        };
        mCountDownTimer.start();
    }


}
